<template>
  <basic-dialog
    width="60%"
    title="关联商品"
    :visible="visible"
    :showFooter="false"
    :showClose=false
  >
    <basic-form
      ref="formData"
      defaultExpandStatus
      :isScalingBtn="false"
      :hasQueryPermission=false
      :formColumns="formItems"
      :dataSource="formData"
      :handleSearchForm="handleQueryForm"
      :handleClearForm="clearCategorySelect"
      @getFormData="getFormData"
    >
      <BtnRender slot="extensionActions" :render="renderBtnsBar" />
      <!--  -->
      <template slot="category">
        <slot name="categorySelect">
          <CategoryMultipleSelect
            ref="categoryMultiple"
            @selectCategoryCallback="setFormCateUuids"
          />
        </slot>
      </template>
    </basic-form>
    <el-tabs
      v-model="tabsInfo.value"
      @tab-click="handleClickTabs"
      style="margin: 10px"
    >
      <el-tab-pane
        v-for="item in tabsInfo.list"
        :key="item.value"
        :name="item.value"
        :label="item.label"
        :disabled="TableInfo.loading"
      />
    </el-tabs>
    <SkusTable
      ref="skusTable"
      showSelectCol
      showActionCol
      showPagination
      :tableHeight="480"
      :defaultMinWidth="100"
      :dataSource="TableInfo.list"
      :columns="TableInfo.columns"
      :loading="TableInfo.loading"
      :pageSizes="pageSizes"
      :pagination="pagination"
      :total="pagination.total"
      :actionRender="renderTableBtnAction"
      :selectionChange="TableInfo.setSelection"
      @pageChange="handlePageChange"
      @pageSizeSelect="handlePageSizeChange"
    />
  </basic-dialog>
</template>
<script>
import BasicDialog from '@/components/BasicDialog';
import BasicForm from '@/components/BasicForm';
import SkusTable from '@/components/skusTable';
import BtnRender from '@/components/JSXRender/BtnRender';
import CategoryMultipleSelect from '@/components/Category/MultipleSelect';
import { mapState, mapMutations } from 'vuex';
import { ASSOCIATE_TYPES_OPTIONS, ASSOCIATE_TYPES_VALUES } from './constants';
import { getArraysByMaps, getInitFormData, TableInfo } from '@/utils/getUtils';
import { getListPageBtnsBar, getTableAction } from '@/utils/getBtnsRender';
import skusPage from '@/mixins/commodity/skusPage';
export default {
  mixins: [skusPage],
  components: {
    BasicDialog,
    BasicForm,
    SkusTable,
    BtnRender,
    CategoryMultipleSelect
  },
  props: {
    visible: {
      type: Boolean,
      default: false
    },
    formItems: {
      type: Array,
      default: () => []
    },
    tableColumns: {
      type: Array,
      default: () => []
    },
    fetchMethod: {
      type: Function,
      default: () => {}
    },
    getAssociateKey: {
      type: Function,
      default: row => row.skuNo
    },
    isQueryEnter: {
      type: Boolean,
      default: true
    },
    tabsData: { // 关联tab数据
      type: Object,
      default: () => ({
        value: ASSOCIATE_TYPES_VALUES.Unassociated, // 当前初始tab位置
        list: ASSOCIATE_TYPES_OPTIONS, // tab渲染集合
        values: ASSOCIATE_TYPES_VALUES
      })
    },
  },
  data () {
    return {
      formData: getInitFormData(this.formItems),
      tabsInfo: this.tabsData,
      TableInfo: new TableInfo({ columns: this.tableColumns }),
      pageSizes: [10, 100, 1000]
    }
  },
  computed: {
    ...mapState('commonComps/associateGoods', ['associatedRows']),
    // 当前是未关联Tab
    isUnassociated () {
      return this.tabsInfo.value == this.tabsInfo.values.Unassociated
    }
  },
  watch: {
    visible (val) {
      (val && this.isQueryEnter) && this.handleQueryForm()
    }
  },
  methods: {
    ...mapMutations('commonComps/associateGoods', [
      'SET_ROW', 'DELETE_ROW', 'BATCH_SET_ROWS', 'BATCH_DELETE_ROWS', 'SET_RESULTS',
    ]),
    // 渲染按钮操作栏
    renderBtnsBar (h) {
      const associatedBtn = { label: '批量关联', method: this.handleBatchAssociate }
      const unassociatedBtn = { label: '批量取消关联', method: this.handleBatchUnassociate, type: 'default' }
      const confirmBtn = { label: '返回表单', method: this.handleConfirm }
      const btnBars = [this.isUnassociated ? associatedBtn : unassociatedBtn, confirmBtn]
      return getListPageBtnsBar(h, btnBars, null, 'start');
    },
    // 渲染表格操作栏按钮
    renderTableBtnAction (h, { row }) {
      const associatedBtn = { label: '关联', method: this.handleAssociate }
      const unassociatedBtn = { label: '取消关联', method: this.handleUnassociate }
      const actionList = [this.isUnassociated ? associatedBtn : unassociatedBtn]
      return getTableAction({ h, row, actionList })
    },
    // 获取表格数据
    async getTableData () {
      const data = {
        formData: this.formData,
        paginationParams: this.paginationParams,
        associateState: this.tabsInfo.value,
        mapValues: getArraysByMaps(this.associatedRows)
      }
      const cannotSearch = !this.isUnassociated && this.associatedRows.size == 0
      if (cannotSearch) return this.TableInfo.clearList()
      const retData = await this.fetchMethod(data, this.TableInfo.setLoading)
      if (retData) {
        this.TableInfo.setList(retData.results)
        this.setTotalNum(retData.totalNum)
      }
    },
    // 切换关联tabs
    handleClickTabs () {
      this.getTableData()
    },
    // 关联
    handleAssociate (row) {
      this.SET_ROW([row, this.getAssociateKey])
      this.$message.success('关联成功')
      this.getTableData()
    },
    // 取消关联
    handleUnassociate (row) {
      this.DELETE_ROW([row, this.getAssociateKey])
      this.$message.success('取消成功')
      this.getTableData()
    },
    // 批量关联
    handleBatchAssociate () {
      if (this.TableInfo.isNullSelection()) return this.$message.warning('请勾选后操作')
      this.BATCH_SET_ROWS([this.TableInfo.selection, this.getAssociateKey])
      this.$message.success('批量关联成功')
      this.getTableData()
    },
    // 批量取消关联
    handleBatchUnassociate () {
      if (this.TableInfo.isNullSelection()) return this.$message.warning('请勾选后操作')
      this.BATCH_DELETE_ROWS([this.TableInfo.selection, this.getAssociateKey])
      this.$message.success('批量取消成功')
      this.getTableData()
    },
    // 返回表单
    handleConfirm () {
      const results = getArraysByMaps(this.associatedRows)
      this.$emit('getResults', results)
      this.SET_RESULTS(results)
      this.closeDialog()
    },
    // 设置表单分类编码（分类多选默认操作）
    setFormCateUuids (list) {
      this.setFormCategoryData('categoryUuids', list.map(item => item.categoryUuid))
    },
    // 设置表单分类数据
    setFormCategoryData (itemProp, data) {
      this.formData[itemProp] = data
    },
    // 清空品类选择信息
    clearCategorySelect () {
      // eslint-disable-next-line no-unused-expressions
      this.$refs?.categoryMultiple?.clearSelectResult() // 清空多选分类
      this.$emit('clearCategory')
    },
    // 关闭弹框
    closeDialog () {
      this.tabsInfo.value = this.tabsInfo.values.Unassociated // 关闭弹框重置查询Tab为未关联
      this.$emit('update:visible', false)
      this.$emit('updateVisible', false)
    }
  }
}
</script>
